var express = require('express');
var router = express.Router();

const XLSX = require('xlsx');
// 引用项目会议纪要相关的模块
var attachment = require('../db/attachment');
const multer = require('multer');
const fs = require('fs');
const path = require('path');
const iconv = require('iconv-lite'); // 引入 iconv-lite
const htmlDocx = require('html-docx-js');
// 附件类型与目录映射
const typeMap = {
  '会议纪要': 'meeting-notes'
};

// 动态存储配置，自动创建目录
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const { type } = req.body;
    const saveDir = typeMap[type] || 'meeting-notes';
    const uploadPath = path.join(__dirname, '..', 'uploads', saveDir);
    // 自动创建目录
    fs.mkdirSync(uploadPath, { recursive: true });
    cb(null, uploadPath);
  },
  filename: function (req, file, cb) {
    // 生成唯一的文件名，使用时间戳和原始扩展名
    const fileExtension = file.originalname.split('.').pop();
    const uniqueFilename = `${Date.now()}-${Math.random().toString(36).substring(2, 8)}.${fileExtension}`;
    cb(null, uniqueFilename); // 使用生成的唯一文件名保存到磁盘
  }
});

const upload = multer({ storage }); // 先定义 upload
const multiUpload = upload.fields([
  { name: 'file', maxCount: 1 },
  { name: 'cahierFile', maxCount: 1 }
]);

/* 项目会议纪要 */
router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});

//访问路由http://localhost:3000/PIannex/getAttachment
router.get('/getMeetingNotes', async function (req, res) {
  const { keyword } = req.query;
  try {
    let query = {};
    if (keyword) {
      query = {
        $or: [
          { MeetingTime: new RegExp(keyword, 'i') },
          { MeetingName: new RegExp(keyword, 'i') },
          { Participants: new RegExp(keyword, 'i') },
          // { cahier: new RegExp(keyword, 'i') },
          { name: new RegExp(keyword, 'i') },
          { creator: new RegExp(keyword, 'i') },
          { createTime: new RegExp(keyword, 'i') },

        ]
      };
    }
    let result = await attachment.find(query);
    res.json({ code: 200, data: result });
  } catch (err) {
    console.error('获取会议纪要失败:', err);
    res.json({ code: 500, msg: "获取失败" });
  }
});

//添加路由http://localhost:3000/PIannex/addAttachment
router.post('/addAttachment', multiUpload, async function (req, res) {
  try {
    const file = req.files['file'] && req.files['file'][0];
    const cahierFile = req.files['cahierFile'] && req.files['cahierFile'][0];
    const { MeetingTime, MeetingName, Participants, cahier, creator, createTime, type } = req.body;
    let attachmentData = {
      MeetingTime,
      MeetingName,
      Participants,
      cahier,
      creator,
      createTime,
      type: type || '会议纪要'
    };

    // 主附件
    if (file) {
      const saveDir = typeMap[type] || 'meeting-notes';
      const decodedOriginalname = iconv.decode(Buffer.from(file.originalname, 'binary'), 'utf8');
      attachmentData.name = decodedOriginalname;
      attachmentData.url = `/uploads/${saveDir}/${file.filename}`;
      attachmentData.type = decodedOriginalname.split('.').pop().toLowerCase();
    }

    // 会议事项记录附件
    if (cahierFile) {
      const saveDir = typeMap[type] || 'meeting-notes';
      const decodedCahierName = iconv.decode(Buffer.from(cahierFile.originalname, 'binary'), 'utf8');
      attachmentData.cahierName = decodedCahierName;
      attachmentData.cahierUrl = `/uploads/${saveDir}/${cahierFile.filename}`;
    }
    let result = await attachment.create(attachmentData);
    res.json({ code: 200, msg: "添加成功", data: result });
  } catch (err) {
    console.error('添加会议纪要失败:', err);
    res.json({ code: 500, msg: "添加失败" });
  }
});

//删除路由http://localhost:3000/PIannex/deleteAttachment
router.post('/deleteAttachment',multiUpload,async function (req, res) {
  let { _id } = req.body;
  try {
    let result = await attachment.findByIdAndDelete(_id);
    res.json({ code: 200, msg: "删除成功", data: result });
  } catch (err) {
    res.json({ code: 500, msg: "删除失败" });
  }
});

//搜索路由http://localhost:3000/PIannex/searchAttachment
router.get('/searchAttachment', async function (req, res, next) {
  let { keyword } = req.query;
  console.log(req.query, req.body);

  console.log('搜索的用户数据:', keyword);
  try {
    let result = await attachment.find({
      $or: [
        { name: new RegExp(keyword, 'i') },
        { MeetingName: new RegExp(keyword, 'i') }
      ]
    });
    console.log(result);
    res.json({
      code: 200,
      msg: "搜索成功",
      data: result
    });
  } catch (err) {
    console.error('搜索会议纪要失败:', err);
    res.json({
      code: 500,
      msg: "搜索失败"
    });
  }
});
// 修改路由 http://localhost:3000/PIannex/updateAttachment
router.post('/updateAttachment', multiUpload, async function (req, res) {
  try {
    const { _id, MeetingTime, MeetingName, Participants, cahier, creator, createTime, type, fileUrl, fileName, cahierUrl, cahierName } = req.body;
    const file = req.files['file'] && req.files['file'][0];
    const cahierFile = req.files['cahierFile'] && req.files['cahierFile'][0];

    let updateData = {
      MeetingTime,
      MeetingName,
      Participants,
      cahier,
      creator,
      createTime,
      type: type || '会议纪要',
      // 新增这两行
      cahierUrl,
      cahierName
    };

    // 主附件
    if (file) {
      const saveDir = typeMap[type] || 'meeting-notes';
      const decodedOriginalname = iconv.decode(Buffer.from(file.originalname, 'binary'), 'utf8');
      updateData.name = decodedOriginalname;
      updateData.url = `/uploads/${saveDir}/${file.filename}`;
      updateData.type = decodedOriginalname.split('.').pop().toLowerCase();
    } else if (fileUrl && fileName) {
      updateData.url = fileUrl;
      updateData.name = fileName;
      updateData.type = fileName.split('.').pop().toLowerCase();
    }

    // 会议事项记录附件
    if (cahierFile) {
      const saveDir = typeMap[type] || 'meeting-notes';
      const decodedCahierName = iconv.decode(Buffer.from(cahierFile.originalname, 'binary'), 'utf8');
      updateData.cahierName = decodedCahierName;
      updateData.cahierUrl = `/uploads/${saveDir}/${cahierFile.filename}`;
    } else if (cahierUrl && cahierName) {
      updateData.cahierUrl = cahierUrl;
      updateData.cahierName = cahierName;
    }

    let result = await attachment.findByIdAndUpdate(_id, { $set: updateData }, { new: true });
    res.json({ code: 200, msg: "修改成功", data: result });
  } catch (err) {
    console.error('修改会议纪要失败:', err);
    res.json({ code: 500, msg: "修改失败" });
  }
});
// ...existing code...
module.exports = router;